// miniprogram/pages/business/fb/fb.js
const db=wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //分类
    array: ['--请选择--', '男:衣服', '男:裤子', '男:鞋子', '男:其他', '女:衣服', '女:裤子', '女:鞋子', '女:其他'],
    express:['--请选择--',0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
    index: 0,
    index2:0,

    imgbox: [],
    imgbox2:[],
    size: [],
    color: [],

    title: "",
    address:'',
    rmb:'',
    
    fileIDs:[],
    fileIDs2:[],
// // 尺寸&颜色&数量
//     table: [""],
//     table2: [""],
  
    numbers: [],

  },
  return:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  rmb:function(e){
    let value = e.detail.value.replace(/\D/g, '')
    var rmb = parseInt(value)
    if (value==""){
      rmb=0
    }
    console.log(rmb )
    this.setData({
      //parseInt将数字字符串转换成数字
      rmb: rmb
    })
  },
 
  GetAddress: function (e) {
    console.log(e.detail.value)
    this.setData({
      address: e.detail.value
    })
  },
  GetTitle: function (e) {
    console.log(e.detail.value)
    this.setData({
      title: e.detail.value
    })
  },
  
  //分类选择
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  //快递选择
  bindPickerChange2: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index2: e.detail.value
    })
  },


  // 删除照片 &&
  imgDelete1: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.deindex;
    let imgbox = this.data.imgbox;
    imgbox.splice(index, 1)
    that.setData({
      imgbox: imgbox
    });
  },
  // 选择图片 &&&
  addPic1: function (e) {
    var imgbox = this.data.imgbox;
    console.log(imgbox)
    var that = this;
    var n = 5;
    if (5 > imgbox.length > 0) {
      n = 5 - imgbox.length;
    } else if (imgbox.length == 5) {
      n = 1;
    }
    wx.chooseImage({
      count: n, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

        if (imgbox.length == 0) {
          imgbox = tempFilePaths
        } else if (5 > imgbox.length) {
          imgbox = imgbox.concat(tempFilePaths);
        }
        that.setData({
          imgbox: imgbox
        });
      }
    })
  },
  // 删除照片 &&
  imgDelete2: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.deindex;
    let imgbox = this.data.imgbox2;
    imgbox.splice(index, 1)
    that.setData({
      imgbox2: imgbox
    });
  },
  // 选择图片 &&&
  addPic2: function (e) {
    var imgbox = this.data.imgbox2;
    console.log(imgbox)
    var that = this;
    var n = 5;
    if (5 > imgbox.length > 0) {
      n = 5 - imgbox.length;
    } else if (imgbox.length == 5) {
      n = 1;
    }
    wx.chooseImage({
      count: n, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

        if (imgbox.length == 0) {
          imgbox = tempFilePaths
        } else if (5 > imgbox.length) {
          imgbox = imgbox.concat(tempFilePaths);
        }
        that.setData({
          imgbox2: imgbox
        });
      }
    })
  },
  AddColor:function(){
    var color=this.data.color
    color.push("")
    this.setData({
      color: color
    })
  },
  DelectColor:function(e){
    console.log(e.currentTarget.dataset.id)
    var color=this.data.color
    color.splice(e.currentTarget.dataset.id,1);                                                                                 console.log(color)
    this.setData({
      color: color
    })                               
  },
  AddSize:function(){
    var size=this.data.size
    size.push("")
    this.setData({
      size: size
    })
  },
  DelectSize:function(e){
    console.log(e.currentTarget.dataset.id)
    var size=this.data.size
    size.splice(e.currentTarget.dataset.id,1);                                                                                 console.log(size)
    this.setData({
      size: size
    })                               
  },
  // 尺码
  InputSize:function(e){
    var that=this;
    console.log(e)
    console.log(e.detail.value)
    console.log(e.target.dataset.id)
    var index = e.target.dataset.id
    var value = e.detail.value
    var size = that.data.size
    size[index] = value
    console.log(size)
    that.setData({
      size :size
    })
  },

  // 颜色
  InputColor:function(e){
    var that=this;
    console.log(e)
    console.log(e.detail.value)
    console.log(e.target.dataset.id)
    var index = e.target.dataset.id
    var value = e.detail.value
    var color = that.data.color
    color[index] = value
    console.log(color)
    that.setData({
      color:color
    })
  },
  AddGood:function(){
    var that=this
    console.log(this.data.imgbox)
    console.log(this.data.imgbox2)
    if(that.data.imgbox.length!=0&&that.data.title!=''&&that.data.rmb!=''&&that.data.address!=''&&that.data.index!=0&&that.data.index2!=0&&that.data.color.length!=0&&that.data.size.length!=0&&that.data.imgbox2.length!=0){
      //上传图片到云存储
      wx.showLoading({
        title: '发布中',
      })
      let imgbox=that.data.imgbox
      let title=that.data.title
      let rmb=that.data.rmb
      let express=that.data.express[that.data.index2]
      let array=that.data.array[that.data.index]
      let color=that.data.color
      let size=that.data.size
      let imgbox2=that.data.imgbox2
      let address=that.data.address
      console.log(imgbox)
      console.log(title)
      console.log(rmb)
      console.log(express)
      console.log(array)
      console.log(color)
      console.log(size)
      console.log(imgbox2)
      let promiseArr = [];
    for (let i = 0; i < that.data.imgbox.length; i++) {
      promiseArr.push(new Promise((reslove, reject) => {
        let item = this.data.imgbox[i];
        let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
        wx.cloud.uploadFile({
          cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
          filePath: item, // 小程序临时文件路径
          success: res => {
            this.setData({
              fileIDs: that.data.fileIDs.concat(res.fileID)
            });
            console.log(res.fileID)
            reslove();
          },
          fail: console.error
        })
      }));
    }
    Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
      let promiseArr2 = [];
      for (let i = 0; i < that.data.imgbox2.length; i++) {
        promiseArr2.push(new Promise((reslove, reject) => {
          let item = this.data.imgbox2[i];
          let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
          wx.cloud.uploadFile({
            cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              this.setData({
                fileIDs2: that.data.fileIDs2.concat(res.fileID)
              });
              console.log(res.fileID)
              reslove();
            },
            fail: console.error
          })
        }));
      }
      Promise.all(promiseArr2).then(res => {//等数组都做完后做then方法
        var numbers=that.data.numbers
        for(let i=0;i<color.length*size.length;i++){
          numbers[i]=0;
        }
        wx.getUserInfo({
          success: res => {
            // 可以将 res 发送给后台解码出 unionId
            console.log(res.userInfo.nickName)
            console.log(res.userInfo.avatarUrl)
            var avatarUrl=res.userInfo.avatarUrl
            var nickName=res.userInfo.nickName
            
            db.collection('Goods').add({
              data: {
                avatarUrl:avatarUrl,
                nickName:nickName,
                title: title,
                type: array,
                rmb: rmb,
                size: size,
                color: color,
                numbers: numbers,
                fileIDs: this.data.fileIDs,
                fileIDs2: this.data.fileIDs2,
                express:express,
                address:address,
                state:"下架",
                sale:10,
                liulan:0,
                sell:0
              }
            }).then(res => {
              wx.hideLoading();
              wx.showToast({
                title: "发布成功",
              })
              setTimeout(function () {
                that.return()
              }, 1000)
            }).catch(err => {
              wx.hideLoading();
              wx.showToast({
                title: "发布失败",
              })
            })
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            if (this.userInfoReadyCallback) {
              this.userInfoReadyCallback(res)
            }
          }
        })
        
        
      })
      
    })
    }else{
      wx.showToast({
        title: "商品信息不能有空",
        icon:"none"
      })
    }
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})